package com.eds.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * Spring Security 安全配置类
 * 用于配置网关的安全策略，包括认证、授权和跨域设置
 */
@Configuration
@EnableWebFluxSecurity  // 启用WebFlux安全配置
public class SecurityConfig {

    /**
     * 配置Spring Security过滤器链
     * 定义安全规则，包括哪些路径需要认证，哪些可以匿名访问
     */
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        return http
                .csrf().disable()  // 禁用CSRF保护
                .cors().and()  // 启用CORS支持
                .exceptionHandling()
                .authenticationEntryPoint((exchange, ex) -> {
                    System.out.println("Authentication error: " + ex.getMessage());
                    return Mono.fromRunnable(() ->
                            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED));
                }).and()
                .authorizeExchange()  // 开始配置授权规则
                .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()  // 允许所有OPTIONS请求
                .pathMatchers(  // 配置允许匿名访问的路径
                        "/userService/userController/**",  // 用户接口
                        "/captchaService/**",  // 验证码服务
                        "/static/**",  // 静态资源
                        "/*.ico",  // 图标文件
                        "/*.png",  // 图片文件
                        "/*.js",  // JavaScript文件
                        "/*.css",  // CSS文件
                        "/assets/**",  // 资源文件
                        "/",  // 根路径
                        "/login",  // 登录页面
                        "/register",  // 注册页面
                        "/home",  // 首页
                        "/forgot-password",
                        "/phone-login",
                        "/forgot-password",
                        "/user",
                        "/ai-chat",
                        "/phone-reset",
                        "/courses",
                        "/search",
                        "/course/create",
                        "/course/*",
                        "/my-courses",
                        "/notifications",
                        "/order/*"
                ).permitAll()
                .pathMatchers("/userService/**").permitAll()  // 临时允许用户服务和课程服务的所有请求
                .pathMatchers("/captchaService/**").permitAll() // 允许验证码服务所有请求
                .pathMatchers("/aiService/**").permitAll()  // 允许AI服务所有请求
                .pathMatchers("/ordersService/**").permitAll()  // 允许订单服务所有请求
                .pathMatchers("/payService/**").permitAll()  // 允许支付服务所有请求
                .pathMatchers("/notificationService/**").permitAll()  // 允许通知服务所有请求
                .pathMatchers("/searchService/**").permitAll()  // 允许搜索服务所有请求
                .pathMatchers("/courseService/courseController/insertCourse").permitAll()
                .pathMatchers("/courseService/courseController/**").permitAll()
                .pathMatchers("/courseService/courseReviewController/**").permitAll()
                .and()
                .build();
    }

    /**
     * 配置CORS跨域过滤器
     * 设置允许跨域访问的源、方法和头部
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setAllowedOrigins(Arrays.asList(
                "http://localhost:4400",
                "http://192.168.31.182:4400",
                "http://172.20.10.3:4400"
        ));
        corsConfig.addAllowedHeader("*");
        corsConfig.addAllowedMethod("*");
        corsConfig.setAllowCredentials(true);
        corsConfig.addExposedHeader("Authorization");
        corsConfig.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);

        return new CorsWebFilter(source);
    }
}